"""
字符串处理工具模块
"""

import unicodedata
import hashlib
import os

from datetime import date
from collections import OrderedDict

from werkzeug.urls import url_quote
from werkzeug.security import check_password_hash


def verify_password(password, raw_password):
    """
    校验密码是否一致
    :param password:
    :param raw_password:
    :return:
    """

    return check_password_hash(password, raw_password)


def get_info_from_idcard(idcard):
    """
    从身份证号码中得出个人信息：生日、性别、年龄、所属年代
    :param idcard:
    :return:
    """
    today = date.today()
    born = date(int(idcard[6:10]), int(idcard[10:12]), int(idcard[12:14]))

    try:
        birth = born.replace(year=today.year)
    except ValueError:
        birth = born.replace(year=today.year, day=born.day - 1)
    if birth > today:
        age = today.year - born.year - 1
    else:
        age = today.year - born.year

    birthday = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
    # 1：男 2：女
    gender = 1 if int(idcard[-2]) % 2 else 2
    # 年代
    year_section = idcard[8:10]
    # 区域编码
    area_code = idcard[0:2]

    result = dict()
    result.setdefault('age', age)
    result.setdefault('birthday', birthday)
    result.setdefault('gender', gender)
    result.setdefault('year_section', year_section)
    result.setdefault('area_code', area_code)

    return result


def handle_file_name(file_name):
    """
    处理文件名称（解决中文乱码问题）
    :param file_name:
    :return:
    """
    file_names = OrderedDict()
    try:
        file_name = file_name.encode('latin-1')
    except UnicodeEncodeError:
        file_names['filename'] = unicodedata.normalize('NFKD', file_name).encode('latin-1', 'ignore')
        file_names['filename*'] = "UTF-8''{}".format(url_quote(file_name))
    else:
        file_names['filename'] = file_name
    return file_names


def generate_token():
    """
    生成token（安全字符）
    :return:
    """
    return hashlib.sha1(os.urandom(24)).hexdigest()
